﻿using System.Collections.Generic;

namespace Whoot
{
    public class ParallelList : TaskList
    {
        private readonly List<int> _finishedIndeces = new List<int>();

        protected override void OnExecute()
        {
            _finishedIndeces.Clear();
            Progress = 0;
        }

        protected override void OnUpdate()
        {
            if (Tasks.Count == 0)
            {
                EndTask();
                return;
            }

            CheckParallelTask();
        }

        protected override void OnReset()
        {
            foreach (var a in Tasks)
            {
                a.Reset();
            }

            _finishedIndeces.Clear();
        }

        private void CheckParallelTask()
        {
            for (var i = 0; i < Tasks.Count; i++)
            {
                if (_finishedIndeces.Contains(i)) continue;
                var status = Tasks[i].Tick();
                switch (status)
                {
                    case TaskStatus.Failure:
                        Err = Tasks[i].ErrInfo;
                        EndTask(false);
                        Tasks[i].OnFinished?.Invoke(false);
                        return;
                    case TaskStatus.Success:
                        _finishedIndeces.Add(i);
                        Tasks[i].OnFinished?.Invoke(true);
                        break;
                }
            }

            if (_finishedIndeces.Count == Tasks.Count) EndTask();
        }
    }
}